package endoscopic

import (
	"rongyy/src/app"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"time"
)

type SetMsgHistory struct {
	models.BaseModel `xorm:"extends"`
	TemplateId       int64  `xorm:"template_id" json:"template_id"`
	Time             string `xorm:"time" json:"time"`
	PatientId        string `xorm:"patient_id" json:"patient_id"`
	IsSend           int    `xorm:"is_send" json:"is_send"`
}

func (pm *SetMsgHistory) TableName() string {
	return "set_msg_history"
}

func (pm *SetMsgHistory) Insert() error {
	_, err := app.DB().Insert(pm)
	if err != nil {
		middlewares.Logger.Println("ERROR - FollowUp Insert failed ", err)
		return err
	}
	return nil
}

func (pm *SetMsgHistory) SelectByPT(pid string, tid int64) (*SetMsgHistory, error) {
	am := &SetMsgHistory{}
	has, err := app.DB().Where("patient_id = ? and template_id=?", pid, tid).Limit(1).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return am, nil
}

func (pm *SetMsgHistory) Update(req *SetMsgHistory) error {
	_, err := app.DB().ID(req.Id).Cols("template_id", "patient_id", "time", "is_send").Update(req)
	if err != nil {
		middlewares.Logger.Println("ERROR - type Update failed ", err)
		return err
	}
	return nil
}

func (pm *SetMsgHistory) SelectById(id int64) (*SetMsgHistory, error) {
	am := &SetMsgHistory{}
	has, err := app.DB().Where("id = ? ", id).Limit(1).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return am, nil
}

func (pm *SetMsgHistory) SelectByList(limit int, start int) ([]SetMsgHistory, int64, error) {
	data := make([]SetMsgHistory, 0)
	s := app.DB().Table("set_msg_history")
	total, err := s.Limit(limit, limit*start).Desc("created_at").FindAndCount(&data)
	if err != nil {
		return nil, 0, err
	}
	return data, total, nil
}

func (pm *SetMsgHistory) SelectAll() ([]SetMsgHistory, error) {
	timestamp := time.Now() //1504079553
	h, _ := time.ParseDuration("24h")
	timestamp = timestamp.Add(h)
	//时间戳转Time 再转 string
	timeNow := time.Unix(timestamp.Unix(), 0) //2017-08-30 16:19:19 +0800 CST

	timeString := timeNow.Format("2006-01-02") //2015-06-15 08:52:32
	data := make([]SetMsgHistory, 0)
	s := app.DB().Table("set_msg_history")
	s.Where("is_send=? and time=?", 0, timeString)
	_, err := s.Desc("created_at").FindAndCount(&data)
	if err != nil {
		return nil, err
	}
	return data, nil
}
